package com.alib.springcloud.ribbonrule.impl;

import com.alib.springcloud.ribbonrule.ImpleRoundRobinRule;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Component //作为组件，能够被@ComponentScan扫描得到
public class ImpleRoundRobinRuleImpl implements ImpleRoundRobinRule {

    // 原子整数
    private AtomicInteger atI = new AtomicInteger(0);

    /**
     * CAS自旋锁实现自增
     */
    public final int increment() {
        int now, next;
        do {
            now = this.atI.get();
            next = now >= 2147483647 ? 0 : now + 1;
        } while (!this.atI.compareAndSet(now, next));
        return next;
    }

    /**
     * 轮询核心算法： 递增的请求次数 % 服务集群数量  = 实际调用集群下标
     * */
    @Override
    public ServiceInstance getServiceInstance(List<ServiceInstance> serviceInstances) {
        return serviceInstances.get(increment() % serviceInstances.size());
    }

}
